<?php

namespace MoChat\App\Statistic\Action\Binding;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 会员绑定统计总数据
 * @Controller
 */
class TotalNumber extends AbstractAction
{

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/statisticBinding/total", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        //微信联系人总数
        $totalPerson=Db::table('work_contact')->count();
        //已绑定客户的微信联系人
        $bindingMemberPerson=Db::table('work_contact')->join('client_contact_pivot as pivot','pivot.contact_id','=','work_contact.id')->count(Db::raw('mc_work_contact.id'));
        //未绑定客户的微信联系人
        $unboundMemberPerson=bcsub($totalPerson,$bindingMemberPerson,0);
        //已绑定多客户的微信联系人
        $bindingMoreMemberPerson=Db::table('work_contact')->join('client_contact_pivot as pivot','pivot.contact_id','=','work_contact.id')->groupBy(['work_contact.id'])->havingRaw("COUNT(*) > 1")->count();
        //绑定多联系人的会员
        $bindingMorePersonMember=Db::table('work_contact')->join('client_contact_pivot as pivot','pivot.contact_id','=','work_contact.id')->groupBy(['pivot.client_id'])->havingRaw("COUNT(*) > 1")->count();

        //绑定多员工的联系人
        $bindingMoreEmployeePerson=Db::table('work_contact_employee')->groupBy(['contact_id'])->havingRaw("COUNT(*) > 1")->count();
        return [
            'unboundClientPerson' => $unboundMemberPerson,//未绑定客户的微信联系人
            'bindingClientPerson' => $bindingMemberPerson,//已绑定客户的微信联系人
            'bindingMoreClientPerson' => $bindingMoreMemberPerson,//已绑定多客户的微信联系人
            'bindingMorePersonClient' => $bindingMorePersonMember,//绑定多微信联系人的客户
            'bindingMoreEmployeePerson' => $bindingMoreEmployeePerson,//绑定多员工的微信联系人
        ];
    }
}
